// 引入接口文件
import { addFun,queryInfo,queryByCompet,getProjectByCompet,queryByRg,editFun} from './kernelGoodsDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  btnLoading: false,
  actionType: 'add',
  count: 2,
  distributionNameList: [],
  query: {
    "month": "",
    "Corecompet": [],
  }
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          if (query.actionType == 'edit') {
              dispatch({type: 'queryInfo',payload: {id:query.id}})
          }
          if (query.actionType != 'edit') {
              dispatch({type: 'queryByCompet',payload: {}})
          }
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
      // 查询记录
      *queryInfo({payload}, {put, select, call}){
          let {query} = yield select(state => state[tmpModule.namespace])
          let params = { 
            id: payload.id,
          }
          const { success,result} = yield call(queryInfo, {...params})
          if(success){
            query.month = result.moth
            query.Corecompet[0] = result.corecompet
            yield put({type: 'updateStore',payload: {query}})
          }
      },
      *getProjectByCompet({payload}, {put, select, call}){
        let {distributionNameList} = yield select(state => state[tmpModule.namespace])
        let params = { 
          project:payload.item.productId
        }
        const { success,result} = yield call(getProjectByCompet, {...params})
        if(success){
          distributionNameList = result
          yield put({type: 'updateStore',payload: {distributionNameList}})
        }
      },
      *queryByRg({payload}, {put, select, call}){
        let {query} = yield select(state => state[tmpModule.namespace])
        if(!query.month){
            message.warning('请先选择统计月份')
            return
        }
        if(!payload.value){
            message.warning('请先选择我司主推业态')
            return
        }
        let params = { 
          project:payload.item.productId,
          date: query.month,
          type: payload.value,
        }
        const { success,result} = yield call(queryByRg, {...params})
        if(success){
          for(var item of query.Corecompet){
              if(item.id== payload.tempId){
                item.companyAmount = result.companyAmount
                item.companyAverage = result.companyAverage
              }
              if(item.key== payload.tempId){
                item.companyAmount = result.companyAmount
                item.companyAverage = result.companyAverage
              }
          }
          yield put({type: 'updateStore',payload: {query}})
        }
      },
       // 查询竞品
      *queryByCompet({payload}, {put, select, call}){
        let {query} = yield select(state => state[tmpModule.namespace])
        let params = {}
        const { success,result} = yield call(queryByCompet, params)
        if(success){  
          query.Corecompet = result
          yield put({
            type: 'updateStore',
            payload: {query}
          })
        }
      },
      *submit({payload},{put,select,call}){
        let {btnLoading,query,actionType} = yield select(state => state[tmpModule.namespace])
        if(actionType != 'edit'){
          let params =  query
          let tempList = query.Corecompet
          let find = false;
          let arr = []
          for (var i = 0; i < tempList.length; i++) {
              for (var j = i + 1; j < tempList.length; j++) {
                  if (tempList[i].companyType == tempList[j].companyType 
                    &&tempList[i].productId == tempList[j].productId
                    ){
                       arr.push(tempList[i])
                       arr.push(tempList[j])
                       find = true; break;
                      }
              }
              if (find) break;
          }
          if(find == true){
            message.warning("同一个项目,不允许重复业态，请调整！")
            return false
          }
          btnLoading = true
          yield put({type: 'updateStore', payload: {btnLoading}})
          let { success, msg, data } = yield call(addFun, {...params})
          let flag = success.toString()
          if(flag){
            btnLoading = false
            yield put({type: 'updateStore', payload: {btnLoading}})
          }
          if(success){
            message.success('保存成功')
            hashHistory.push({
              pathname: '/home/predictManage/weekReport',
              query: {tabsType:'3'}
            })
          }
        }
        if(actionType == 'edit'){
          let params =  query.Corecompet[0]
          btnLoading = true
          yield put({type: 'updateStore', payload: {btnLoading}})
          let { success, msg, data } = yield call(editFun, {...params})
          let flag = success.toString()
          if(flag){
            btnLoading = false
            yield put({type: 'updateStore', payload: {btnLoading}})
          }
          if(success){
            message.success('修改成功')
            hashHistory.push({
              pathname: '/home/predictManage/weekReport',
              query: {tabsType:'3'}
            })
          }
        }
      },
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
